<template>
    <el-drawer title="我是标题" :visible.sync="dialogVisible" :with-header="false" class="demand_box" size='600px' @close="resetForm('addForm')">
        <div class="flexbox flexcolumn height_100" v-loading="loading" element-loading-spinner="el-icon-loading" element-loading-background="rgba(0, 0, 0, 0)">
            <div class="demand_head flexbox flexcenter flexbetween">
                <span class="demand_title">{{type=='add'?"创建":"修改"}}需求</span>
                <span class="icon_btn icon_btn_32"><img src="../../assets/img/close_check.svg" alt="" @click="resetForm('addForm')"></span>
            </div>
            <div class="demand_center flex gaydm_bg">
                <el-form label-position="top" style="margin-top:-10px" :model="addForm" size="medium" :hide-required-asterisk='true' ref="addForm" :rules="addVideoMultiSzRules" class="dialog_form">
                    <div class="step_boxs flexbox flexcenter">
                        <div class="flexbox flexcenter" style="margin-right:20px">
                            品牌/产品：
                            <span>{{brand_name}}-{{product_name}}</span>
                        </div>
                        <div class="flexbox flexcenter" style="margin-right:20px">
                            业务场景：
                            <span>{{filters.chanelName2(addForm.channel)}}-{{filters.sceneFilter(addForm.business_scene)}}</span>
                        </div>
                        <div class="flexbox flexcenter" style="margin-right:20px">
                            需求总数：
                            <span>{{quantity}}</span>
                        </div>
                        <div class="flexbox flexcenter">
                            剩余需求：
                            <span>{{getLast<0?"已超出":getLast}}</span>
                        </div>
                    </div>
                    <template v-if="addForm.member.length>0">
                        <div class="demands_box" v-for="(item,index) in addForm.member" :key="index">
                            <div class="demands_head flexbox flexcenter flexbetween">
                                <div class="demands_num flexbox flexcenter">
                                    需求 {{index+1}}
                                </div>
                                <div class="flexbox flexcenter">
                                    <div class="demands_btn blue" @click="copyItem(item)">复制需求</div>
                                    <div class="demands_btn red" @click="deletItem(index)">删除</div>
                                </div>
                            </div>
                            <div class="demands_title flexbox flexcenter flexbetween font_14 color_01">编导信息</div>
                            <el-form-item label="编导人员" :prop="`member.${index}.centre_uid`" :rules="{required: true, message: '请选择', trigger: ['blur','change']}" size="small">
                                <el-select v-model="item.centre_uid" filterable placeholder="编导" style="width:100%">
                                    <el-option label="默认剪辑" :value="0"></el-option>
                                    <el-option :label="item_uid.nickname" :value="item_uid.id" v-for="item_uid in centreList" :key="item_uid.id"></el-option>
                                </el-select>
                            </el-form-item>
                            <el-form-item label="脚本总数" :prop="`member.${index}.quantity`" :rules="{required: true, message: '请选择', trigger: ['blur','change']}" size="small">
                                <el-input-number class="resetNumBtn" v-model="item.quantity" controls-position="right" :min="1" style="width:80px"></el-input-number>
                            </el-form-item>
                            <div class="demands_title flexbox flexcenter flexbetween font_14 color_01">
                                <div>剪辑信息</div>
                                <!-- <el-link type="primary" icon="el-icon-plus" :underline="false" @click="addClip(index)">添加</el-link> -->
                            </div>
                            <el-row :gutter="12" v-if="item.executor_uid.length>0">
                                <el-col :span="12" v-for="(items,indexs) in item.executor_uid" :key="indexs">
                                    <el-form-item :label="`剪辑${indexs+1}`" size="small" style="margin-bottom:10px">
                                        <div class="flexbox flexcenter flexbetween">
                                            <el-form-item label="" :prop="`member.${index}.executor_uid.${indexs}.user_id`" :rules="{required: true, message: '请选择', trigger: ['blur','change']}" size="small">
                                                <el-select v-model="items.user_id" placeholder="剪辑" style="width:150px" :disabled="true">
                                                    <el-option :label="item_id.nickname" :value="item_id.id" v-for="item_id in optimiList" :key="item_id.id"></el-option>
                                                </el-select>
                                            </el-form-item>
                                            <el-form-item label="" :prop="`member.${index}.executor_uid.${indexs}.quantity`" :rules="{required: true, message: '请选择', trigger: ['blur','change']}" size="small">
                                                <el-input-number class="resetNumBtn" v-model="items.quantity" controls-position="right" :min="0" style="width:80px"></el-input-number>
                                            </el-form-item>
                                            <!-- <el-link icon="el-icon-delete" :underline="false" @click="deletClip(index,indexs)"></el-link> -->
                                        </div>
                                    </el-form-item>
                                </el-col>
                            </el-row>
                            <div class="clip_text" v-else>暂无剪辑人员，请到【固定人员配置】中设置</div>
                        </div>
                    </template>
                    <div class="add_list" v-else @click="addMemberList">添加需求</div>
                </el-form>

            </div>
            <div class="demand_footer flexbox flexcenter gaydm_bg">
                <el-button plain size="small" class="el-button-width" @click="resetForm">取 消</el-button>
                <el-button type="primary" size="small" class="el-button-width" @click="submitForm('addForm')" :loading="loading" :disabled='loading'>完成创建</el-button>
            </div>
        </div>
    </el-drawer>
</template>

<script>
export default {
    props:["queryInfo"],
    name: "",
    data() {
        return {
            loading: false,
            dialogVisible: false,
            brandSelect: {},
            brandList: [], //品牌列表
            productList: [], //产品列表
            sceneList: [], //业务场景列表
            optimiList: [], //剪辑列表
            centreList: [], //核心创意人
            memberList: [],
            clip_index: null,
            quantity: null,
            brand_name: "",
            product_name: "",
            addForm: {
                project_id: null,
                year: null,
                week: null,
                brand_id: null,
                product_id: null,
                channel: null,
                business_scene: null,
                group: null,
                member: [],
            },
        };
    },
    computed:{
        getLast(){
            let all = this.quantity
            let list = this.addForm.member
            let has_num = null
            let las_num = null
            for(let i in list){
                has_num +=list[i].quantity
            }
            las_num = all - has_num
            return  las_num
        }
    },
    created() {
        // this.getDetails();
        // this.getOptimization();
        // this.getCentreList();
    },
    methods: {
        getData(data) {
            this.dialogVisible = true;
            this.addForm.project_id = data.id;
            this.addForm.year = data.year;
            this.addForm.week = data.week;
            this.addForm.group = data.group;
            this.addForm.brand_id = data.brand_id;
            this.addForm.product_id = data.product_id;
            this.addForm.channel = data.channel;
            this.addForm.business_scene = data.business_scene;
            this.quantity = data.quantity;
            this.brand_name = data.brand_name;
            this.product_name = data.product_name;
            this.getMemberList();
            this.getOptimization();
            this.getCentreList();
        },

        //获取小组成员
        async getMemberList() {
            this.loading = true;
            const { data: res } = await this.$http.post(
                "adminapi/demandsz/editorGroupList",
                {
                    group: this.addForm.group,
                }
            );
            if (res.code !== 200) {
                this.loading = false;
                this.$message.error(res.msg);
                return;
            } else {
                this.loading = false;
                let arr = [];
                for (let i in res.data) {
                    arr.push({
                        quantity: 0,
                        user_id: res.data[i].id,
                    });
                }
                this.memberList = arr;
                this.getDetails();
            }
        },

        // 获取剪辑列表
        async getOptimization() {
            const { data: res } = await this.$http.post(
                "adminapi/company/szClipperList"
            );
            if (res.code !== 200) {
                this.$message.error(res.msg);
                return;
            } else {
                this.optimiList = res.data;
            }
        },

        // 获取核心创意人列表
        async getCentreList() {
            const { data: res } = await this.$http.post(
                "adminapi/company/szCentreList"
            );
            if (res.code !== 200) {
                this.$message.error(res.msg);
                return;
            } else {
                this.centreList = res.data;
            }
        },

        getAdmin(list) {
            let is_true = list.some((item) => {
                return item.id == this.userinfo.id;
            });
            this.is_admin = is_true;
        },

        // 获取详情
        async getDetails() {
            let queryInfo = {
                year: this.addForm.year,
                week: this.addForm.week,
                brand_id: this.addForm.brand_id,
                product_id: this.addForm.product_id,
                channel: this.addForm.channel,
                group: this.addForm.group,
                business_scene: this.addForm.business_scene,
            };
            const { data: res } = await this.$http.post(
                "adminapi/demandsz/demandDetail",
                queryInfo
            );
            if (res.code !== 200) {
                this.$message.error(res.msg);
                return;
            } else {
                let arr = [];
                for (let i in res.data) {
                    arr.push({
                        quantity: res.data[i].quantity,
                        executor_uid: this.getHasNumber(
                            this.memberList,
                            res.data[i].executor_uid
                        ),
                        // executor_uid: res.data[i].executor_uid,
                        centre_uid: res.data[i].centre_uid,
                    });
                }
                this.addForm.member = arr;
                this.loading = false;
            }
        },

        getHasNumber(data1, data2) {
            let list = JSON.parse(JSON.stringify(data1));
            let list2 = JSON.parse(JSON.stringify(data2));
            for (let i in list) {
                for (let a in list2) {
                    if (list[i].user_id == list2[a].user_id) {
                        list[i].quantity = list2[a].quantity;
                    }
                }
            }
            return list;
        },

        // 提交添加
        submitForm(formName) {
            this.$refs[formName].validate(async (valid) => {
                if (valid) {
                    // let queryInfo = JSON.parse(JSON.stringify(this.addForm));
                    // delete queryInfo.quantity;
                    if (this.getAllData() > this.quantity) {
                        this.$message.error("脚本总数不能大于需求总数");
                        return;
                    }
                    if (this.getAllClip()) {
                        this.$message.error(
                            "需求" +
                                (Number(this.clip_index) + 1) +
                                ":剪辑总数不能大于脚本总数"
                        );
                        return;
                    }
                    this.loading = true;
                    const { data: res } = await this.$http.post(
                        "adminapi/demandsz/demandEdit_v2",
                        this.addForm
                    );
                    if (res.code !== 200) {
                        this.$message.error(res.msg);
                        this.loading = false;
                        return;
                    } else {
                        this.$message({
                            message: "保存成功",
                            type: "success",
                        });
                        this.loading = false;
                        this.$emit("getDataList", this.queryInfo.page);
                        this.$emit("getDataCount");
                        this.$emit("getStatistics");
                        this.resetForm(formName);
                    }
                } else {
                    this.loading = false;
                    return false;
                }
            });
        },

        // 复制列表
        copyItem(item) {
            let list = JSON.parse(JSON.stringify(item));
            this.addForm.member.push(list);
        },

        // 添加列表
        addMemberList() {
            let userinfo = JSON.parse(window.localStorage.getItem("userinfo"));
            let is_true = this.centreList.some((item) => {
                return item.id == userinfo.id;
            });
            this.addForm.member.push({
                centre_uid: is_true ? userinfo.id : 0,
                quantity: 1,
                executor_uid: [...this.memberList],
            });
        },

        // 删除列表
        deletItem(index) {
            this.addForm.member.splice(index, 1);
        },

        // 添加剪辑
        addClip(index) {
            this.addForm.member[index].executor_uid.push({
                user_id: "",
                quantity: 1,
            });
        },

        // 删除剪辑
        deletClip(index, indexs) {
            this.addForm.member[index].executor_uid.splice(indexs, 1);
        },

        // 关闭重置表单
        resetForm(formName) {
            // this.$refs[formName].resetFields();
            this.brandSelect = {};
            this.addForm = {
                project_id: null,
                year: null,
                week: null,
                brand_id: null,
                product_id: null,
                channel: null,
                business_scene: null,
                group: null,
                member: [],
            };
            this.dialogVisible = false;
        },

        getAllData() {
            let num = null;
            let list = this.addForm.member;
            for (let i in list) {
                num += list[i].quantity;
            }
            return num;
        },

        getAllClip() {
            let list = this.addForm.member;
            var is_true = false;
            for (let i in list) {
                let num2 = list[i].quantity;
                let num = null;
                for (let s in list[i].executor_uid) {
                    num += list[i].executor_uid[s].quantity;
                    if (num > num2) {
                        this.clip_index = i;
                        is_true = true;
                    }
                }
            }
            return is_true;
        },
    },
    components: {},
};
</script>

<style scoped>
.add_list {
    line-height: 40px;
    text-align: center;
    font-size: 14px;
    color: #4475ff;
    background: #fff;
    border-radius: 6px;
    cursor: pointer;
    margin-top: 10px;
}
.step_boxs {
    
    background: #fff;
    border-radius: 6px;
    padding: 10px 20px;
    font-size: 14px;
    color: #616c85;
    margin-top: 10px;
    flex-wrap: wrap;
}
.step_boxs span {
    color: #17233d;
    max-width: 230px;
    overflow: hidden;
    height: 14px;
    line-height: 14px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}

.gaydm_bg {
    background: #f2f4f7;
}
.demands_box {
    background: #fff;
    border-radius: 6px;
    margin-top: 12px;
    padding: 20px;
}
.demands_num {
    background: rgba(165, 177, 209, 0.1);
    border-radius: 3px;
    height: 28px;
    padding: 0 8px;
    font-size: 14px;
    color: #616c85;
}
.demands_num span {
    border-left: 1px solid #ebebeb;
    margin: 0 9px;
    height: 12px;
}
.demands_btn {
    line-height: 28px;
    height: 28px;
    width: 72px;
    border-radius: 4px;
    font-size: 14px;
    text-align: center;
    margin-left: 8px;
    cursor: pointer;
}
.demands_btn.blue {
    color: #4475ff;
    background: rgba(22, 93, 255, 0.05);
}
.demands_btn.red {
    color: #fe6262;
    background: rgba(254, 98, 98, 0.05);
}
.demands_title {
    margin-top: 24px;
    margin-bottom: 12px;
}
/deep/ .resetNumBtn .el-icon-arrow-up:before {
    content: "\e78f";
}
/deep/ .resetNumBtn .el-input-number__decrease,
/deep/ .resetNumBtn .el-input-number__increase {
    background: #fff;
}
/deep/ .resetNumBtn.el-input-number.is-controls-right .el-input__inner {
    padding-left: 5px;
    padding-right: 35px;
}
.clip_text {
    text-align: center;
    font-size: 14px;
    color: #b4b7bd;
    margin-top: 5px;
}
/deep/ .demand_center.gaydm_bg .el-input.is-disabled .el-input__inner {
    color: #17233d;
}
</style>


